package com.szholly.pro.watergas_server.ps.controller;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.szholly.data.general.PageInfo;
import com.szholly.data.general.RowBase;
import com.szholly.plug.form.excel.utils.StringUtil;
import com.szholly.pro.watergas_server.common.data.DataUtil;
import com.szholly.pro.watergas_server.common.web.BaseController;
import com.szholly.pro.watergas_server.common.web.RequestUnit;
import com.szholly.pro.watergas_server.ps.service.DataValidateService;
import com.szholly.pro.watergas_server.ps.service.OnlineMonitorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
@RequestMapping("/MonitorDataValidate/*")
public class MonitorDataValidateController extends BaseController {

	@Autowired
	DataValidateService dataValidateService;
	
	@Autowired
	OnlineMonitorService onlineMonitorService;

	protected Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 获取全部运维事件的有效性
	 * 
	 * @param resq
	 *            请求参数，包含 WWTP_ID-污水处理厂ID FLOW_NAME-流向 START_TIME-开始时间 END_TIME-结束时间
	 * @param res
	 */
	@RequestMapping(value = "/queryAllJobParamValidationList")
	public void queryAllJobParamValidationList(HttpServletRequest resq, HttpServletResponse res) {
		Map<String, String> params = getParams();
		List<Map<String, String>> jobParamValidationList = dataValidateService.queryAllJobParamValidationList(params);
		JSONArray jsonObj = JSONArray.fromObject(jobParamValidationList);
		outString(jsonObj.toString());
	}

	/**
	 * 分子项查看日常巡检的有效性
	 * 
	 * @param resq
	 * @param res
	 */
	@RequestMapping(value = "/queryDailyInspectionTypeValidationList")
	public void queryDailyInspectionTypeValidationList(HttpServletRequest resq, HttpServletResponse res) {
		Map<String, String> params = getParams();

		List<Map<String,String>> listJobs = dataValidateService.getParamJobList(params);
		Map<String, String> jobInfo =  (listJobs==null||listJobs.size()==0)?
										null:listJobs.get(0);
		if (jobInfo == null)
			return;

		params.put("JOB_NAME", jobInfo.get("JOB_NAME"));
		params.put("JOB_CYCLE", jobInfo.get("JOB_CYCLE"));
		params.put("JOB_CYCLE_DESC", jobInfo.get("JOB_CYCLE_DESC"));
		params.put("JOB_TOLERANCE", jobInfo.get("JOB_TOLERANCE"));
		params.put("JOB_TOLERANCE_DESC", jobInfo.get("JOB_TOLERANCE_DESC"));

		List<Map<String, String>> jobValidationList = dataValidateService.getDailyInspectionTypeValidationList(params);
		if (jobValidationList == null)
			return;

		JSONArray jsonObj = JSONArray.fromObject(jobValidationList);
		outString(jsonObj.toString());
	}
	

	/**
	 * 获取设备运转率统计结果
	 * 
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryDeviceOperationRate")
	public void queryDeviceOperationRate(HttpServletRequest resq, HttpServletResponse res) 
			throws Exception {
		Map<String, String> params = getParams();

		List<Map<String, String>> deviceOprRateList 
			= dataValidateService.getStationDeviceOperateRateList(params);
		
		if (deviceOprRateList == null || deviceOprRateList.size() < 1)
			return;

		JSONArray jsonObj = JSONArray.fromObject(deviceOprRateList);
		outString(jsonObj.toString());
	}

	/**
	 * 获取数采仪在线率
	 * 
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryMNOnlineRate")
	public void queryMNOnlineRate(HttpServletRequest resq, HttpServletResponse res)
			throws Exception {
		Map<String, String> params = getParams();

		Map<String, String> mnOnlineRate = dataValidateService.getStationMNOnlineRate(params);
		if (mnOnlineRate == null)
			return;

		JSONObject jsonObj = JSONObject.fromObject(mnOnlineRate);
		outString(jsonObj.toString());
	}

	/**
	 * 获取数据传输有效率统计结果
	 * 
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryDataTransferValidation")
	public void queryDataTransferValidation(HttpServletRequest resq, HttpServletResponse res) throws Exception {
		// 1、获取数据传输率C=D/E
		// 2、获取数据有效率 P=S/M
		// 3、数据传输有效率 Z=C*P
		
		Map<String, String> params = getParams();

		Map<String, String> mnInfo = onlineMonitorService.getStationDataCollectMN(params.get("STATION_ID"));
		if (mnInfo == null)
			return;

		params.put("MN", mnInfo.get("MN"));

		Map<String, String> rateMap = dataValidateService.getDataTransferValidation(params);
		JSONObject jsonObj = JSONObject.fromObject(rateMap);
		outString(jsonObj.toString());
	}
	
	/**
	 * 获取污水处理厂流量
	 * @throws Exception 
	 */
	@RequestMapping(value = "/getWWTPFlow")
	public void getWWTPFlow(HttpServletRequest resq, HttpServletResponse res) throws Exception {
		Map<String,String> params = new HashMap<String,String>();
		String wwtp_id = RequestUnit.getParameter("WWTP_ID");
		params.put("wwtp_id", wwtp_id);
		
		int year = Integer.parseInt(RequestUnit.getParameter("MEASURE_YEAR"));
		int start_month = Integer.parseInt(RequestUnit.getParameter("MEASURE_START_MONTH"));
		int end_month = Integer.parseInt(RequestUnit.getParameter("MEASURE_END_MONTH"));
		String start = getFirstDayOfMonth(year,start_month);
		String end = getLastDayOfMonth(year,end_month);
		
		params.put("start", start);
		params.put("end", end);
		
		//获取时间段内最大最小流量读数
		double max = 0d;
		double min = 0d;
		List<RowBase> list = onlineMonitorService.getWWTPFlow(params, null);
		if(list!=null && list.size()>0){
			max = list.get(list.size()-1).getSafeDouble("RTD");
			if(list.size()>1){
				min = list.get(0).getSafeDouble("RTD");
			}
		}else{
			return;
		}
		
		//获取污水处理单价
		double price = 1d;
		list = onlineMonitorService.getWWTPProcessPrice(params, null);
		if(list!=null && list.size()>0){
			price = list.get(0).getSafeDouble("PROCESS_PRICE");
		}
		
		PageInfo pageInfo = DataUtil.getPageInfo();
		list = onlineMonitorService.getWWTPFlow(params, pageInfo);
		JSONObject json = DataUtil.listToJSONObject(list, null, pageInfo);
		json.put("totalFlow", max-min);
		json.put("price", price);
		outString(json.toString());
	}
	
	/**
	 * 获取某月的最后一天
	 * @param year
	 * @param month
	 * @return
	 */
    private String getLastDayOfMonth(int year,int month)
    {
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR,year);
        //设置月份
        cal.set(Calendar.MONTH, month-1);
        //获取某月最大天数
        int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        //设置日历中月份的最大天数
        cal.set(Calendar.DAY_OF_MONTH, lastDay);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String lastDayOfMonth = sdf.format(cal.getTime());
         
        return lastDayOfMonth;
    }
    /**
	 * 获取某月的第一天
	 * @param year
	 * @param month
	 * @return
	 */
    private String getFirstDayOfMonth(int year,int month)
    {
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR,year);
        //设置月份
        cal.set(Calendar.MONTH, month-1);
        //获取某月最大天数
        int firstDay = cal.getActualMinimum(Calendar.DAY_OF_MONTH);
        //设置日历中月份的最大天数
        cal.set(Calendar.DAY_OF_MONTH, firstDay);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String lastDayOfMonth = sdf.format(cal.getTime());
         
        return lastDayOfMonth;
    }

    /**
     * 获取请求参数
     * @return
     */
	private Map<String,String> getParams(){
		String strWWTP_ID = RequestUnit.getString("WWTP_ID");
		String strFLOW_TYPE = RequestUnit.getString("FLOW_NAME");
		String strSTATION_ID = this.getStationId(strWWTP_ID, strFLOW_TYPE);
		
		String strSTART_TIME = RequestUnit.getString("START_TIME");
		String strEND_TIME = RequestUnit.getString("END_TIME");
		String strJOB_ID = RequestUnit.getString("JOB_ID");
		String strINSPECTION_TYPE = RequestUnit.getString("INSPECTION_TYPE");
		
		Map<String, String> params = new HashMap<String, String>();
		if(StringUtil.IsNotNullOrEmpty(strSTATION_ID)){
			params.put("STATION_ID", strSTATION_ID);
		}
		if(StringUtil.IsNotNullOrEmpty(strSTART_TIME)){
			params.put("START_TIME", strSTART_TIME);
		}
		if(StringUtil.IsNotNullOrEmpty(strEND_TIME)){
			params.put("END_TIME", strEND_TIME);
		}
		if(StringUtil.IsNotNullOrEmpty(strJOB_ID)){
			params.put("JOB_ID", strJOB_ID);
		}
		if(StringUtil.IsNotNullOrEmpty(strINSPECTION_TYPE)){
			params.put("INSPECTION_TYPE", strINSPECTION_TYPE);
		}
		
		return params;
	}
}
